package com.chushouya.manager.service.admin.impl;


import com.chushouya.manager.dto.admin.login.AdminUserAuthDTO;
import com.chushouya.manager.dto.admin.login.LoginUser;
import com.chushouya.manager.service.admin.AdminTokenService;
import com.general.framework.core.constant.Constants;
import com.general.framework.core.exception.CodeEnum;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.IdTakes;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Strings;
import com.general.framework.data.redis.RedisCache;
import com.general.framework.web.utils.IpAddressUtil;
import com.general.framework.web.utils.IpUtils;
import com.general.framework.web.utils.ServletUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 * @author leejean team
 */
@Component
@Slf4j
@RefreshScope
public class AdminTokenServiceImpl implements AdminTokenService {

    // 令牌秘钥
    @Value("${com.chushouya.manager.login.admin.secret}")
    private String secret;

    // 令牌有效期 分钟
    @Value("${com.chushouya.manager.login.admin.expireTime}")
    private long expireTime;

    // 单点登录
    @Value("${com.chushouya.manager.login.admin.singleSignOn:false}")
    private Boolean singleSignOn;

    private static final long MILLIS_SECOND = 1000;

    private static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_20_MINUTE = 20 * MILLIS_MINUTE;

    @Resource
    private RedisCache redisCache;

    @Resource
    private AdminTokenService adminTokenService;

    @Override
    public String createToken(LoginUser loginUser) {
        String userId = String.format("%08d", loginUser.getUserId());
        String loginUserKey = Strings.format("{}:{}", userId, IdTakes.takeRandomCode(10));
        final String jwtToken = buildJwtToken(loginUserKey);
        loginUser.setJwtToken(jwtToken);
        loginUser.setLoginUserKey(loginUserKey);
        this.setUserAgent(loginUser);
        if (this.singleSignOn && Objects.equals("no", loginUser.getRemoteAssistance())) {
            // 单点登录，异地下线
            Collection<String> keys = redisCache.keys(Constants.ADMIN_LOGIN_TOKEN_KEY.concat(userId).concat(":*"));
            if (Lists.isNotEmpty(keys)) {
                for (String key : keys) {
                    redisCache.deleteObject(key);
                }
            }
        }
        this.refreshToken(loginUser);
        return jwtToken;
    }

    @Override
    public LoginUser getLoginUser(String token) {
        // 获取请求携带的令牌
        if (Strings.isNotEmpty(token)) {
            try {
                String loginUserCacheKey = getLoginTokenKey(this.parseLoginUserKey(token));
                final LoginUser loginUser = redisCache.getCacheObject(loginUserCacheKey);
                if (Objects.nonNull(loginUser)) {
                    adminTokenService.verifyToken(loginUser);
                }
                return loginUser;
            } catch (Exception e) {
                log.error("获取用户身份信息失败:{}", e.getMessage());
            }
        }
        return null;
    }

    @Override
    public AdminUserAuthDTO authToken(String token) {
        LoginUser loginUser = adminTokenService.getLoginUser(token);
        if (Objects.isNull(loginUser)) {
            throw Ex.business(CodeEnum.UNAUTHORIZED);
        }
        AdminUserAuthDTO adminUserAuth = new AdminUserAuthDTO();
        adminUserAuth.setAdminUserId(loginUser.getUserId());
        adminUserAuth.setUserName(loginUser.getUserName());
        adminUserAuth.setRoles(loginUser.getRoles());
        adminUserAuth.setPermissions(loginUser.getPermissions());
        adminUserAuth.setExtendInfo(loginUser.getExtraInfo());
        return adminUserAuth;
    }

    @Async
    @Override
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_20_MINUTE) {
            refreshToken(loginUser);
        }
    }

    @Override
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + (expireTime * MILLIS_MINUTE));
        String loginTokenKey = getLoginTokenKey(loginUser.getLoginUserKey());
        redisCache.setCacheObject(loginTokenKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    @Override
    public void delLoginToken(String jwtToken) {
        if (Strings.isNotEmpty(jwtToken)) {
            String loginUserCacheKey = this.getLoginTokenKey(parseLoginUserKey(jwtToken));
            redisCache.deleteObject(loginUserCacheKey);
        }
    }

    @Override
    public void delLoginToken(Long adminUserId) {
        String userId = String.format("%08d", adminUserId);
        Collection<String> keys = redisCache.keys(Constants.ADMIN_LOGIN_TOKEN_KEY.concat(userId).concat(":*"));
        if (Lists.isNotEmpty(keys)) {
            for (String key : keys) {
                redisCache.deleteObject(key);
            }
        }
    }

    /**
     * 设置用户代理信息
     * @param loginUser 登录信息
     */
    private void setUserAgent(LoginUser loginUser) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginUser.setIpAddr(ip);
        loginUser.setLoginLocation(IpAddressUtil.getAddress(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     * @param loginUserKey 登录用户key
     * @return 令牌
     */
    private String buildJwtToken(String loginUserKey) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, loginUserKey);
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 从令牌中获取数据声明
     * @param jwtToken 令牌
     * @return 数据声明
     */
    private String parseLoginUserKey(String jwtToken) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwtToken)
                    .getBody();
            return (String) claims.get(Constants.LOGIN_USER_KEY);
        } catch (Exception e) {
            throw Ex.systemError("parseToken Exception");
        }
    }

    private String getLoginTokenKey(String loginUserKey) {
        return Constants.ADMIN_LOGIN_TOKEN_KEY + loginUserKey;
    }
}
